package com.java110.mall.chain.partner.adapter.hibo.utils;


import java.util.Iterator;
import java.util.Map;
import java.util.TreeMap;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class SignUtils {
    private static final Logger log = LoggerFactory.getLogger(SignUtils.class);
    private static final String SIGN = "sign";

    public SignUtils() {
    }

    public static String sign(TreeMap<String, String> params, String secret) {
        if (StringUtils.isBlank(secret)) {
            log.error("签名-secret为空");
            throw new RuntimeException("secret为空");
        } else if (params != null && !params.isEmpty()) {
            try {
                return MD5Utils.md5Str(secret + MD5Utils.getString(params) + secret).toUpperCase();
            } catch (Exception var3) {
                log.error("erp-open client-计算签名异常-e：{}", var3.getMessage(), var3);
                throw new RuntimeException("erp-open client-计算签名异常");
            }
        } else {
            log.error("签名-TreeMap为空");
            throw new RuntimeException("TreeMap为空");
        }
    }

    public static boolean checkSign(TreeMap<String, String> params, String secret) throws Exception {
        String sign = (String)params.get("sign");
        return sign.equals(getSign(params, secret));
    }

    private static String getSign(TreeMap<String, String> param, String secret) throws Exception {
        return MD5Utils.md5Str(concatParams(param, secret)).toUpperCase();
    }

    private static String concatParams(TreeMap<String, String> treeMap, String secret) {
        StringBuilder sb = new StringBuilder(secret);
        int i = treeMap.size();
        Iterator var4 = treeMap.entrySet().iterator();

        while(var4.hasNext()) {
            Map.Entry<String, String> entry = (Map.Entry)var4.next();
            if ("sign".equals(entry.getKey())) {
                --i;
            } else {
                sb.append((String)entry.getKey()).append("=").append((String)entry.getValue());
                if (i > 1) {
                    sb.append("&");
                }

                --i;
            }
        }

        sb.append(secret);
        return sb.toString();
    }
}